package com.red.servlet;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.red.entity.User;
import com.red.mapper.UserMapper;
import com.red.utils.Result;
import com.red.utils.SqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "loginServlet", value = "/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/json;charset=utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            String jsonStr = JSONUtil.toJsonStr(Result.fail("用户名或密码不能为空"));
            response.getWriter().write(jsonStr);
            response.sendRedirect("/jsp_servlet/login.html");
            return;
        }

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryBean.getBean();

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int count = mapper.login(new User(username, password));
        if (count>0){
            HttpSession session1 = request.getSession();
            session1.setAttribute("username",username);
            session1.setAttribute("password",password);

            response.getWriter().write(JSONUtil.toJsonStr(Result.ok(count)));

            response.sendRedirect("/jsp_servlet/1.html");

            return;
        }

        Result fail = Result.fail("没有该用户");
        String jsonStr = JSONUtil.toJsonStr(fail);
        response.getWriter().write(jsonStr);
        response.sendRedirect("/jsp_servlet/login.html");

        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doGet(request,response);
    }
}
